package jgo.plugins.middleware;

import jgo.Context;
import jgo.JGo;
import jgo.Handler;
import jgo.core.MiddlewarePlugin;
import jgo.plugins.server.HttpContext;

public class CorsMiddleware extends MiddlewarePlugin {
	@Override
	public void init(JGo gin) {
		// 初始化逻辑（如果需要）
	}

	@Override
	public String name() {
		return "cors";
	}

	@Override
	public void handle(Context ctx2, Handler next) {

		HttpContext ctx = (HttpContext) ctx2;
		ctx.header("Access-Control-Allow-Origin", "*");
		ctx.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		ctx.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

		if ("OPTIONS".equalsIgnoreCase(ctx.getMethod())) {
			((HttpContext) ctx.status(200)).end();
		} else {
			next.handle(ctx);
		}
	}
}